package com.example.slack.config;

import com.alibaba.fastjson.JSON;
import com.slack.api.bolt.App;
import com.slack.api.bolt.AppConfig;
import com.slack.api.model.event.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.slack.api.methods.response.chat.ChatPostMessageResponse;

import java.util.regex.Pattern;

@Configuration
public class SlackApp {
    @Bean
    public App initSlackApp() {
        AppConfig config = new AppConfig();
        config.setSingleTeamBotToken("xoxb-5118834517970-7648408831154-7qofPkl0P2pxKziEw7QZMi50");
        config.setSigningSecret("109f143fa83ff2369e518e17f53c7a4b");
        App app = new App(config);
        app.command("/hello", (req, ctx) -> {
            return ctx.ack("What's up?");
        });

        app.event(ReactionAddedEvent.class, (payload, ctx) -> {
            ReactionAddedEvent event = payload.getEvent();
            if (event.getReaction().equals("white_check_mark")) {
                ChatPostMessageResponse message = ctx.client().chatPostMessage(r -> r
                        .channel(event.getItem().getChannel())
                        .threadTs(event.getItem().getTs())
                        .text("<@" + event.getUser() + "> Thank you! We greatly appreciate your efforts :two_hearts:"));
                if (!message.isOk()) {
                    ctx.logger.error("chat.postMessage failed: {}", message.getError());
                }
            }
            return ctx.ack();
        });
        app.event(MessageEvent.class, (payload, ctx) -> {
            MessageEvent event = payload.getEvent();
            System.out.println("-----------------------------------");
            System.out.println(JSON.toJSONString(event));
            System.out.println("-----------------------------------");
            return ctx.ack();
        });
        app.event(AppMentionEvent.class, (payload, ctx) -> {
            AppMentionEvent event = payload.getEvent();
            System.out.println("-----------------------------------");
            System.out.println(JSON.toJSONString(event));
            System.out.println("-----------------------------------");
            return ctx.ack();
        });
        Pattern sdk = Pattern.compile(".*hello.*", Pattern.CASE_INSENSITIVE);
        app.message(sdk, (payload, ctx) -> {
            System.out.println(payload.getEvent().getUser());
            ctx.say("Hello, <@" + payload.getEvent().getUser() + ">");
            return ctx.ack();
        });
        return app;
    }
}